<script setup lang="ts">
import { ref, watch, computed } from "vue";
import { getPatientNames } from "@/api/hospital";
interface EditData {
  id?: number;
  patient_id?: string;
  patientName?: string;
  deptName?: string;
  doctorName?: string;
  outpatient_code?: string;
  inpatient_code?: string;
  first_visit?: string;
  genderStr?: string;
  condition?: string;
  [key: string]: any;
}

// 定义接收的 props
const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false,
  },
  isEdit: {
    type: Boolean,
    default: false,
  },
  editData: {
    type: Object as () => EditData,
    default: () => ({}),
  },
  deptList: {
    type: Array,
    default: () => [],
  },
});

// 查询参数
const form = ref({});
const recordRef = ref();

const rules = ref({
  patientName: [{ required: true, message: "请输入患者姓名", trigger: "blur" }],
  dept_id: [{ required: true, message: "请选择所属科室", trigger: "blur" }],
  first_visit: [{ required: true, message: "请输入首诊时间", trigger: "blur" }],
  doctorName: [{ required: true, message: "请输入首诊医生", trigger: "blur" }],
});

const diseases = ref([
  { name: "高血压", treatment_status: "0", status: "0" },
  { name: "糖尿病", treatment_status: "0", status: "0" },
  { name: "骨质疏松", treatment_status: "0", status: "0" },
  { name: "子宫肌瘤", treatment_status: "0", status: "0" },
  {
    name: "卵巢良性肿瘤",
    treatment_status: "0",
    status: "0",
  },
  {
    name: "乳腺良性肿瘤",
    treatment_status: "0",
    status: "0",
  },
]);

// 计算合并后的疾病数据
const mergedDiseases = computed(() => {
  const merged = [...diseases.value];

  // 确保 editData.disease 存在且是数组
  const realDisease = props.editData?.disease;
  if (realDisease && Array.isArray(realDisease)) {
    realDisease.forEach((actual) => {
      const index = merged.findIndex((item) => item.name === actual.name);
      if (index !== -1) {
        merged[index] = { ...merged[index], ...actual };
      }
    });
  }

  return merged;
});

// 计算转换后的表格数据
const diseaseTableData = computed(() => {
  const data = mergedDiseases.value;
  return Array.from({ length: Math.ceil(data.length / 2) }, (_, i) => {
    const index = i * 2;
    return {
      name_1: data[index]?.name || "",
      treatment_status_1: data[index]?.treatment_status || "0",
      status_1: data[index]?.status || "0",
      name_2: data[index + 1]?.name || "",
      treatment_status_2: data[index + 1]?.treatment_status || "0",
      status_2: data[index + 1]?.status || "0",
    };
  });
});

// 监听数据变化，初始化表单
watch(
  () => props.editData,
  (newData) => {
    form.value = { ...newData };

    // 设置吸烟相关字段的默认值
    if (form.value.smoking === undefined) {
      form.value.smoking = "2"; // 默认从不吸烟
    }
    if (form.value.passive_smoking === undefined) {
      form.value.passive_smoking = "0"; // 默认否
    }

    if (props.editData.disease && Array.isArray(props.editData.disease)) {
      props.editData.disease.forEach((item) => {
        if (item.name === "被动吸烟") {
          form.value.passive_smoking = item.status;
        }
        if (item.name === "吸烟") {
          form.value.smoking = item.status;
        }
      });
    }

    delete form.value.disease;
  },
  { immediate: true }
);

const emit = defineEmits(["update:modelValue", "confirm"]);

const submitForm = () => {
  const formData = { ...form.value };
  formData["disease"] = [];
  diseaseTableData.value.forEach((item) => {
    formData["disease"].push({
      name: item.name_1,
      treatment_status: item.treatment_status_1,
      status: item.status_1,
    });
    formData["disease"].push({
      name: item.name_2,
      treatment_status: item.treatment_status_2,
      status: item.status_2,
    });
  });
  formData["disease"].push({
    name: "被动吸烟",
    status: form.value.passive_smoking,
  });
  formData["disease"].push({
    name: "吸烟",
    status: form.value.smoking,
  });

  delete formData.smoking;
  delete formData.passive_smoking;

  emit("confirm", {
    originalData: props.editData,
    formData: formData,
  });
  if (recordRef.value) {
    recordRef.value.clearValidate();
  }
  emit("update:modelValue", false);
};

const resetForm = () => {
  // 清除表单验证状态
  if (recordRef.value) {
    recordRef.value.clearValidate();
  }
  emit("update:modelValue", false);
};

const onDialogOpened = () => {
  // 对话框打开时清除表单验证状态
  if (recordRef.value) {
    recordRef.value.clearValidate();
  }
};

const patients = ref([]);
function getPatients() {
  getPatientNames().then((response) => {
    if (response.code == 200) {
      patients.value = response.data;
    }
  });
}
getPatients();
</script>
<template>
  <el-dialog
    :model-value="modelValue"
    :title="isEdit ? '编辑病历' : '新增病历'"
    width="80%"
    @update:model-value="$emit('update:modelValue', $event)"
    @opened="onDialogOpened"
    @close="resetForm"
  >
    <el-scrollbar height="600px" class="scrollbar">
      <el-form :model="form" :rules="rules" ref="recordRef" label-width="80px">
        <div class="dialog-title">
          <h2>一、一般情况</h2>
          <el-row>
            <el-col :span="8">
              <el-form-item label="患者姓名" prop="patientName">
                <el-select
                  filterable
                  v-model="form.patient_id"
                  placeholder="请选择患者"
                >
                  <el-option
                    v-for="item in patients"
                    :key="item.patient_id"
                    :label="item.patientName"
                    :value="item.patient_id"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="门诊号" prop="outpatient_code">
                <el-input
                  v-model="form.outpatient_code"
                  placeholder="请输入门诊号"
                  maxlength="20"
                />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="住院号" prop="inpatient_code">
                <el-input
                  v-model="form.inpatient_code"
                  placeholder="请输入住院号"
                  maxlength="20"
                />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="所属科室" prop="dept_id">
                <el-select
                  filterable
                  v-model="form.dept_id"
                  placeholder="请选择所属科室"
                >
                  <el-option
                    v-for="dict in deptList"
                    :key="dict.id"
                    :label="dict.name"
                    :value="dict.id"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="首诊时间" prop="first_visit">
                <el-date-picker
                  v-model="form.first_visit"
                  type="date"
                  placeholder="请输入首诊时间"
                />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="首诊医生" prop="doctorName">
                <el-input
                  v-model="form.doctorName"
                  placeholder="请输入首诊医生"
                  maxlength="50"
                />
              </el-form-item>
            </el-col>

            <el-col :span="24">
              <el-form-item label="病情描述" prop="condition">
                <el-input
                  v-model="form.condition"
                  placeholder="请输入病情描述"
                  type="textarea"
                />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="现病史" prop="present_illness">
                <el-input
                  v-model="form.present_illness"
                  placeholder="请输入现病史"
                  type="textarea"
                />
              </el-form-item>
            </el-col>
          </el-row>
        </div>
        <div class="dialog-title">
          <h2>二、个人史与相关病史</h2>
          <el-form-item
            label="1.现在或既往吸烟吗？"
            prop="smoking"
            label-position="left"
            label-width="180px"
          >
            <el-radio-group v-model="form.smoking">
              <el-radio label="1">现在吸烟</el-radio>
              <el-radio label="2">从不吸烟</el-radio>
              <el-radio label="3">曾经吸烟</el-radio>
              <el-radio label="4">已戒烟</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item
            label="您在工作单位或家里经常被动吸烟吗？"
            prop="passive_smoking"
            label-position="left"
            label-width="280px"
          >
            <el-radio-group v-model="form.passive_smoking">
              <el-radio label="1">是</el-radio>
              <el-radio label="0">否</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-text>2.您是否有以下相关病史(可多选):</el-text>
          <el-row style="margin-left: 5px; margin-right: 5px">
            <el-table
              :data="diseaseTableData"
              width="100%"
              border
              style="width: 100%"
              table-layout="fixed"
            >
              <el-table-column prop="name_1" label="疾病" header-align="center">
                <template #default="scope">
                  <el-text style="margin-right: 10px">{{
                    scope.row.name_1
                  }}</el-text>
                  <el-radio-group v-model="scope.row.status_1">
                    <el-radio label="1">是</el-radio>
                    <el-radio label="0">否</el-radio>
                  </el-radio-group>
                </template>
              </el-table-column>
              <el-table-column
                width="150"
                header-align="center"
                prop="treatment_status_1"
                label="是否接受过正规治疗"
                label-width="10px"
              >
                <template #default="scope">
                  <el-radio-group v-model="scope.row.treatment_status_1">
                    <el-radio label="1">是</el-radio>
                    <el-radio label="0">否</el-radio>
                  </el-radio-group>
                </template>
              </el-table-column>
              <el-table-column prop="name_2" label="疾病" header-align="center">
                <template #default="scope">
                  <el-text style="margin-right: 10px">{{
                    scope.row.name_2
                  }}</el-text>
                  <el-radio-group v-model="scope.row.status_2">
                    <el-radio label="1">是</el-radio>
                    <el-radio label="0">否</el-radio>
                  </el-radio-group>
                </template>
              </el-table-column>
              <el-table-column
                width="150"
                header-align="center"
                prop="treatment_status_2"
                label="是否接受过正规治疗"
                label-width="10px"
              >
                <template #default="scope">
                  <el-radio-group v-model="scope.row.treatment_status_2">
                    <el-radio label="1">是</el-radio>
                    <el-radio label="0">否</el-radio>
                  </el-radio-group>
                </template>
              </el-table-column>
            </el-table>
          </el-row>
        </div>
      </el-form>
    </el-scrollbar>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="resetForm">取消</el-button>
        <el-button type="primary" @click="submitForm">确定</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<style scoped>
.dialog-title {
  border-bottom: 1px solid #eee;
  padding-bottom: 10px;
}

.dialog-title h2 {
  margin-top: 10px;
  margin-bottom: 20px;
  color: #333;
}
</style>
